articles

Home / DeveloperSection / Articles / Security in ASP.NET

Security in ASP.NET

priyanka kushwaha6911 27-Feb-2015

 In this article, I’m explaining about Security in .NET

Authentication:

It is the process of ensuring the user’s identity and authenticity ASP.NET allows four types of mode:

1.      Windows(Default)

2.      Forms

3.      Passport

4.      None 

Windows:

 The window authentication provider allows you to authenticate users based on their window accounts. This provider uses IIS to perform the actual authentication and then passes the authenticated identity to your code. This is the default provider for ASP.NET.

Forms:

The forms authentication provider uses custom HTML forms to collect authentication information and allows you to use you own logic to authenticate users. The user’s credentials are then stored in a cookie for use during the session. 

Passport:

The passport authentication provider uses Microsoft’s passport service to authenticate users. Passport is a forms-based authentication service. 

None (Custom):

Specify “None” as the authentication provider when users are not authenticated at all or if you plan to develop custom authentication code. 

Federated Identity: 

It refers to where the user stores their credentials. Alternatively, FID can be viewed as a way to connect Identity Management systems together. In FID, a user's credentials are always stored with the "home" organization (the "identity provider"). When the user logs into a service, instead of providing credentials to the service provider, the service provider trusts the identity provider to validate the credentials. So the user never provides credentials directly to anybody but the identity provider. 

Authorization

Authorization is a process by which a server determines if the client has permission to use a resource or access a file.

<authorization> 
     <allow roles ="Admin"/>
      <deny users ="*"/>
</authorization>           

Membership

The membership feature is built around two central classes:

1.      Membership

2.       MembershipUser.

The membership class provides methods for creating users (represented by the MembershipUser class), as well as common administration methods for managing users. The users that are created with the membership class represent the authenticated identities for an ASP.NET application. The key class in the Membership framework is the membership class, which has methods like:

1.      CreateUser

2.      DeleteUser

3.      GetAllUsers

4.      UpdateUser

5.      ValidateUser

Example:
 <membershipdefaultProvider="Demo_MemberShipProvider">

      <providers>

        <addconnectionStringName="cnn"enablePasswordRetrieval="false"

         enablePasswordReset="true"requiresQuestionAndAnswer="true"applicationName="/"

         requiresUniqueEmail="false"passwordFormat="Hashed"maxInvalidPasswordAttempts="5"

         minRequiredPasswordLength="5"minRequiredNonalphanumericCharacters="0"

         passwordAttemptWindow="10"passwordStrengthRegularExpression=""

         name="Demo_MemberShipProvider"type="System.Web.Security.SqlMembershipProvider" />

      </providers>

    </membership>

 
Role Manager

The central management class for role Manager is the Roles class. The Roles class provider methods for creating roles and assigning users to roles. It also provides common administration methods for managing role information.

<roleManager enabled="true" cacheRolesInCookie="true" cookieName="DemoRoles" defaultProvider="SqlProvider"> 
      <providers>
        <add connectionStringName="cnn" applicationName="/" name="SqlProvider"
         type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    </roleManager>

 

Create a LoginForm
Login.aspx

<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="login1.aspx.cs"Inherits="AuthenticationApplication.login1"%>

 

<!DOCTYPEhtml>

 

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

    <title></title>

</head>

<body>

    <formid="form1"runat="server">

    <div>

 

        <div>

            <h3><ahref="RegistrationFile.aspx"id="login"runat="server">New Registration</a></h3>

        </div>

        <asp:LoginID="Login1"runat="server"OnAuthenticate="Login1_Authenticate">

 

        </asp:Login>

    </div>

    </form>

</body>

</html>

 

Login.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Security;

namespace AuthenticationApplication

{

    publicpartialclasslogin1 : System.Web.UI.Page

    {

        protectedvoid Page_Load(object sender, EventArgs e)

        {

            if (User.Identity.IsAuthenticated)

            {

                Response.Redirect("HomePage.aspx");

            }

        }

 

        protectedvoid Login1_Authenticate(object sender, AuthenticateEventArgs e)

        {

       

            if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)

            {

              FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);

            }

            else

                Response.Write("Invalid login");

      }

    }

}

Registration.aspx


<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="RegistrationFile.aspx.cs"Inherits="AuthenticationApplication.RegistrationFile"%>

 <!DOCTYPEhtml>

 <htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

    <title></title>

</head>

<body>

    <formid="form1"runat="server">

     <asp:CreateUserWizardID="CreateUserWizard1"runat="server"OnContinueButtonClick="CreateUserWizard1_ContinueButtonClick"OnCreatedUser="CreateUserWizard1_CreatedUser">

            <WizardSteps>

                <asp:CreateUserWizardStepID="CreateUserWizardStep1" runat="server">

                </asp:CreateUserWizardStep>

                <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">

                </asp:CompleteWizardStep>

            </WizardSteps>

        </asp:CreateUserWizard>

    </form>

</body>

</html>

RegistrationForm.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Security;

namespace AuthenticationApplication

{

    publicpartialclassRegistrationFile : System.Web.UI.Page

    {

        protectedvoid Page_Load(object sender, EventArgs e)

        {

 

        }

 

        protectedvoid CreateUserWizard1_CreatedUser(object sender, EventArgs e)

        {

            MembershipCreateStatus status;

            Membership.CreateUser(CreateUserWizard1.UserName, CreateUserWizard1.Password, CreateUserWizard1.Email, CreateUserWizard1.Question, CreateUserWizard1.Answer, true, out status);

            if (Roles.RoleExists("Admin"))

            {

                Roles.AddUserToRole(CreateUserWizard1.UserName, "Admin");

            }

            else

            {

                Roles.CreateRole("Admin");

                Roles.AddUserToRole(CreateUserWizard1.UserName, "Admin");

            }

        }

 

        protectedvoid CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)

        {

            Response.Redirect("login1.aspx");

        }

    }

}

Create a MasterPage.Master

<%@MasterLanguage="C#"AutoEventWireup="true"CodeBehind="MasterPage.master.cs"Inherits="AuthenticationApplication.MasterPage"%>

 

<!DOCTYPEhtml>

 

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

    <title></title>

    <asp:ContentPlaceHolderID="head"runat="server">

    </asp:ContentPlaceHolder>

</head>

<body>

    <formid="form1"runat="server">

        <div>

               <divstyle="float:right">

                 <asp:ButtonID="btnlogin"runat="server"Text="login"OnClick="btnlogin_Click"  />

                </div>

        </div>

    <div>

        <asp:ContentPlaceHolderID="ContentPlaceHolder1"runat="server"OnPreRender="ContentPlaceHolder1_PreRender">

       

        </asp:ContentPlaceHolder>

    </div>

    </form>

</body>

</html>

Create MasterPage.Master.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.Security;

using System.Security.Principal;

namespace AuthenticationApplication

{

    publicpartialclassMasterPage : System.Web.UI.MasterPage

    {

        protectedvoid Page_Load(object sender, EventArgs e)

        {

            if (this.Context.User.Identity.Name != null)

            {

                btnlogin.Text = "logout";

            }

          

        }

 

        protectedvoid btnlogin_Click(object sender, EventArgs e)

        {

            if (this.Context.User.Identity.Name != null)

            {

                FormsAuthentication.SignOut();

                btnlogin.Text = "login";

                Response.Redirect("~/login1.aspx");

            }

          

        }

 

        protectedvoid ContentPlaceHolder1_PreRender(object sender, EventArgs e)

        {

          

        }

 

    }

}


Create HomePage.aspx


<%@PageTitle=""Language="C#"MasterPageFile="~/MasterPage.Master"AutoEventWireup="true"CodeBehind="HomePage.aspx.cs"Inherits="AuthenticationApplication.HomePage"%>

<asp:ContentID="Content1"ContentPlaceHolderID="head"runat="server">

</asp:Content>

<asp:ContentID="Content2"ContentPlaceHolderID="ContentPlaceHolder1"runat="server">

    WelCome home page

</asp:Content>

 


Create  Global.asax.cs


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.SessionState;

 

namespace AuthenticationApplication

{

    publicclassGlobal : System.Web.HttpApplication

    {

 

        protectedvoid Application_Start(object sender, EventArgs e)

        {

            if (User!=null &&!User.Identity.IsAuthenticated)

                Response.Redirect("login1.aspx");

        }

 

        protectedvoid Session_Start(object sender, EventArgs e)

        {

 

        }

 

        protectedvoid Application_BeginRequest(object sender, EventArgs e)

        {

           

             

        }

 

        protectedvoid Application_AuthenticateRequest(object sender, EventArgs e)

        {

 

        }

 

        protectedvoid Application_Error(object sender, EventArgs e)

        {

 

        }

 

        protectedvoid Session_End(object sender, EventArgs e)

        { 

        }

 

        protectedvoid Application_End(object sender, EventArgs e)

        {

            FormsAuthentication.SignOut();

        }

    }

}

 

 

Create an Admin Folder
Add an Admin.aspx file

<%@PageTitle=""Language="C#"MasterPageFile="~/MasterPage.Master"AutoEventWireup="true"CodeBehind="Admin.aspx.cs"Inherits="AuthenticationApplication.Admin.Admin"%>

<asp:ContentID="Content1"ContentPlaceHolderID="head"runat="server">

</asp:Content>

<asp:ContentID="Content2"ContentPlaceHolderID="ContentPlaceHolder1"runat="server">

    <divstyle="float:right">

        </div>

    <divstyle="height:450px;">

<h2>Admin Panel:</h2>

<table>

<tr>

<td>

    <asp:TextBoxID="txtrolename"runat="server"></asp:TextBox>

    <asp:ButtonID="btnCreateRole"runat="server"Text="CreateRole"OnClick="btnCreateRole_Click"/>

</td>

</tr>

<tr>

<td>

<table>

<tr>

<td>Available Users</td>

<td>Available Roles</td>

</tr>

<tr>

<tdstyle="height: 72px">

    <asp:ListBoxID="lstusers"runat="server"Height="95px"Width="105px"></asp:ListBox>

</td>

<tdstyle="height: 72px">

    <asp:ListBoxID="lstRoles"runat="server"Height="92px"Width="95px"></asp:ListBox>

</td>

</tr>

</table>

</td>

</tr>

<tr>

<td>

    <asp:ButtonID="btnAssignRoleToUser"runat="server"Text="Assign Role To User"Width="175px"OnClick="btnAssignRoleToUser_Click"/>

</td>

</tr>

<tr>

<td>

    <asp:ButtonID="btnRemoveUserFromUser"runat="server"Text="Remove User From Role"OnClick="btnRemoveUserFromUser_Click"/>

   

</td>

</tr>

<tr>

<td>

    <asp:ButtonID="btnRemoveRoles"runat="server"Text="Delete Roles"Width="176px"OnClick="btnRemoveRoles_Click"style="height: 26px"/>

</td>

</tr>

<tr>

<td>

    <asp:LabelID="Label1"runat="server"></asp:Label>

</td>

</tr>

</table>

</div>

       

</asp:Content>

 
Write Admin.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Web.Security;

 

namespace AuthenticationApplication.Admin

{

    publicpartialclassAdmin : System.Web.UI.Page

    {

        SqlConnection cnn = newSqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);

        protectedvoid Page_Load(object sender, EventArgs e)

        {

 

            if (!IsPostBack)

            {

                BindRoles();

                BindUsers();

                Label1.Text = "";

            }

 

        }

        publicvoid BindRoles()

        {

            SqlDataAdapter sda = newSqlDataAdapter("select RoleName from aspnet_Roles", cnn);

            DataSet ds = newDataSet();

            sda.Fill(ds, "Roles");

            lstRoles.DataSource = ds;

            lstRoles.DataTextField = "RoleName";

            lstRoles.DataTextField = "RoleName";

            lstRoles.DataBind();

        }

        publicvoid BindUsers()

        {

            SqlDataAdapter da = newSqlDataAdapter("select UserName from aspnet_users", cnn);

            DataSet ds = newDataSet();

            da.Fill(ds, "Roles");

            lstusers.DataSource = ds;

            lstusers.DataTextField = "UserName";

            lstRoles.DataValueField = "RoleName";

            lstusers.DataBind();

        }

 

        protectedvoid btnAssignRoleToUser_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                if (!Roles.IsUserInRole(lstRoles.SelectedItem.Text))

                {

                    Roles.AddUserToRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);

                    BindUsers();

                    BindRoles();

                    Label1.Text = "User Assigned To User Successfully";

                }

                else

                {

                    Label1.Text = "Role(s) Already Assigned To User";

                }

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

 

        protectedvoid btnRemoveUserFromUser_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                Roles.RemoveUserFromRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);

                BindUsers();

                BindRoles();

                Label1.Text = "Role(s) Removed Successfully";

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

 

        protectedvoid btnRemoveRoles_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                Roles.DeleteRole(lstRoles.SelectedItem.Text);

                BindUsers();

                BindRoles();

                Label1.Text = "Role(s) Removed Successfully";

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

 

        protectedvoid btnCreateRole_Click(object sender, EventArgs e)

        {

            Label1.Text = "";

            try

            {

                if (!Roles.RoleExists(txtrolename.Text))

                {

                    Roles.CreateRole(txtrolename.Text);

                    BindUsers();

                    BindRoles();

                    Label1.Text = "Role(s) Created Successfully";

                }

                else

                {

                    Label1.Text = "Role(s) Already Exists";

                }

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

}

 

Add in web.config file in Admin folder


<?xmlversion="1.0"?>

<configuration>

  <appSettings/>

  <connectionStrings/>

      <system.web>

        <authorization>

        <allowroles ="Admin"/>

        <denyusers ="*"/>

      </authorization>

    </system.web>

 </configuration> 

 

Write in application web.config file

<?xmlversion="1.0"?>

<configuration>

  <appSettings>

    <addkey="ValidationSettings:UnobtrusiveValidationMode"value="None"/>

  </appSettings>

  <connectionStrings>

    <addname="cnn"connectionString="Data Source=YourServerName;Initial Catalog=PriyankaDB; User Id=UserID;Password=UserPassword;"providerName="System.Data.SqlClient"/>

  </connectionStrings>

 

  <system.web>

    <authenticationmode="Forms">

      <formscookieless="UseCookies"defaultUrl="HomePage.aspx"loginUrl="login1.aspx"protection="All"timeout="30"></forms>

    </authentication>

    <membershipdefaultProvider="Demo_MemberShipProvider">

      <providers>

        <addconnectionStringName="cnn"enablePasswordRetrieval="false"

         enablePasswordReset="true"requiresQuestionAndAnswer="true"applicationName="/"

         requiresUniqueEmail="false"passwordFormat="Hashed"maxInvalidPasswordAttempts="5"

         minRequiredPasswordLength="5"minRequiredNonalphanumericCharacters="0"

         passwordAttemptWindow="10"passwordStrengthRegularExpression=""

         name="Demo_MemberShipProvider"type="System.Web.Security.SqlMembershipProvider" />

      </providers>

    </membership>

      <compilationdebug="true"targetFramework="4.5" />

      <httpRuntimetargetFramework="4.5" />

    <roleManagerenabled="true"cacheRolesInCookie="true"cookieName="DemoRoles"defaultProvider="SqlProvider">

      <providers>

        <addconnectionStringName="cnn"applicationName="/"name="SqlProvider"

         type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

      </providers>

    </roleManager>

    </system.web>

  <locationpath="Registration.aspx">

    <system.web>

      <authorization>

        <allowusers="*"/>

      </authorization>

    </system.web>

  </location>

 

</configuration>

 

 

Output:

Security in ASP.NET


Registrationform.aspx

Security in ASP.NET


Admin form access only Admin User



Security in ASP.NET


Leave Comment

Comments

Liked By